<?php

/**
 * 场景分类
 *
 * @author libaoling
 * @time 2015-1-12
 */
class Place_categoryApp extends MallbaseApp
{

    private $_placecate_mod;
    private $_goods_mod;
    protected $page_size = 32;

    public function __construct()
    {
        $this->Place_categoryApp();
    }

    public function Place_categoryApp()
    {
        parent::__construct();

        $this->_placecate_mod = m("placecategory");
        $this->_goods_mod = m("goods");
    }

    public function index()
    {
        $params = $this->_get_parmas();
        if (!isset($params['cate_id']))
        {
            $this->show_warning('请您先选择场景分类!');
            return;
        }

        /* 筛选条件 */
        $this->assign('filters', $this->_get_filter($params));
        $this->assign('param', $params);

        /* 排序 */
        $order_arr = $this->_get_orders();
        $order = (isset($_GET['order']) && isset($order_arr[$_GET['order']])) ? $order_arr[$_GET['order']] : 'g.goods_id DESC';
        $this->assign('orders', trim($_GET['order']));

        $page = $this->_get_page($this->page_size);
        $conditions = $this->_get_conditions($params);

        $cacheServer = cache_server();
        $cacheKey = "place_category_index_" . md5($conditions . $page['limit'] . $order);
        $data = $cacheServer->hGet($this->_placecate_mod->_name, $cacheKey);

        if ($data === false)
        {
            $join = "belongs_to_store, belongs_to_placecategory";
            $table = "wl_goods g LEFT JOIN wl_store s ON g.store_id = s.store_id 
                      LEFT JOIN wl_place_category_goods place_category_goods ON g.goods_id = place_category_goods.goods_id";
            if(strpos($order, 'sales') !== false){
                $join .= ", has_goodsstatistics";
                $table .= " LEFT JOIN wl_goods_statistics goods_statistics ON g.goods_id=goods_statistics.goods_id";
            }
            
            $list = $this->_goods_mod->findAll(array(
                'conditions' => $conditions,
                'fields' => 'DISTINCT g.goods_name, g.start_stock, g.price,g.default_image,s.store_name,s.store_id',
                'join' => $join,
                'order' => $order,
                'limit' => $page['limit'],
            ));

            $sqlCount = "SELECT COUNT(DISTINCT g.goods_id) from {$table} where {$conditions}";
            $page['item_count'] = $this->_goods_mod->db->getOne($sqlCount);
            $this->_format_page($page);

            $data['list'] = $list;
            $data['page'] = $page;
            $cacheServer->hSet($this->_placecate_mod->_name, $cacheKey, $data, $this->_placecate_mod->expire);
        }
        
        foreach ($data['list'] as $key => $goods)
        {
            empty($goods['default_image']) && $data['list'][$key]['default_image'] = Conf::get('default_goods_image');
        }

        /* 当前位置 */
        $this->_curlocal($this->_get_curlocal($params['cate_id']));
        
        $this->assign('page_info', $data['page']); //分页数据
        $this->assign('lists', $data['list']); //商品列表
        $this->assign("cates", $this->_get_child_cates($params['cate_id']));
        /* 配置seo信息 */
        $this->_config_seo($this->_get_seo_info($params['cate_id']));
        $this->import_resource('indexlist.js');
        $this->display("place_category_index.html");
    }

    private function _get_parmas()
    {
        static $res = null;
        if ($res === null)
        {
            $res = array();

            // cate_id 分类
            if (isset($_GET['cate_id']) && intval($_GET['cate_id']) > 0)
            {
                $res['cate_id'] = intval($_GET['cate_id']);
            }

            // start_stock  起订量
            if (!empty($_GET['start_stock']))
            {
                $res['start_stock'] = intval($_GET['start_stock']);
            }

            // price  价格区间
            if (isset($_GET['price']))
            {
                $arr = explode('-', $_GET['price']);
                $min = abs(floatval($arr[0]));
                $max = abs(floatval($arr[1]));
                if ($min * $max > 0 && $min > $max)
                {
                    list($min, $max) = array($max, $min);
                }

                $res['price'] = array(
                    'min' => $min,
                    'max' => $max
                );
            }
        }

        return $res;
    }

    private function _get_orders()
    {
        return array(
            'sales-desc' => 'sales DESC',
            'sales-asc' => 'sales ASC',
            'price-asc' => 'g.price ASC',
            'price-desc' => 'g.price DESC',
            'add_time-desc' => 'g.add_time DESC',
            'add_time-asc' => 'g.add_time ASC',
        );
    }

    private function _get_conditions($params)
    {
        /* 组成查询条件 */
        $conditions = " g.if_show = 1 AND g.closed = 0 AND s.state = 1"; // 上架且没有被禁售，店铺是开启状态,

        /* 分类查询 */
        if (isset($params['cate_id']))
        {
            $cate_ids = $this->_placecate_mod->get_descendant_ids($params['cate_id'], true);
            $conditions .= " AND place_category_goods.cate_id " . db_create_in($cate_ids);
        }

        /* 起订量查询 */
        if (isset($params['start_stock']))
        {
            $conditions .= " AND g.start_stock <= '" . $params['start_stock'] . "'";
        }

        /* 价格查询 */
        if (isset($params['price']))
        {
            $min = $params['price']['min'];
            $max = $params['price']['max'];
            $min > 0 && $conditions .= " AND g.price >= '$min'";
            $max > 0 && $conditions .= " AND g.price <= '$max'";
        }

        return $conditions;
    }

    private function _get_filter($param)
    {
        static $filters = null;
        if ($filters === null)
        {
            $filters = array();

            isset($param['start_stock']) && $filters['start_stock'] = array('key' => 'start_stock', 'name' => LANG::get('start_stock'), 'value' => $param['start_stock']);

            if (isset($param['price']))
            {
                $min = $param['price']['min'];
                $max = $param['price']['max'];
                if ($min <= 0)
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => LANG::get('le') . ' ' . price_format($max));
                }
                elseif ($max <= 0)
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => LANG::get('ge') . ' ' . price_format($min));
                }
                else
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => price_format($min) . ' - ' . price_format($max));
                }
            }
        }

        return $filters;
    }
    
    private function _get_child_cates($cate_id)
    {
        $cates = $this->_get_nav_placecategory();
        $parents = $this->_placecate_mod->get_ancestor($cate_id, true);
        $parent_id = $parents[0]['cate_id'];
        if(isset($parents[1]) && isset($cates[$parent_id]['children'][$parents[1]['cate_id']])){
            $cates[$parent_id]['children'][$parents[1]['cate_id']]['select'] = true;
            $cates[$parent_id]['select'] = true;
        }
        return isset($cates[$parent_id]) ? $cates[$parent_id] : array();
    }
    
    private function _get_curlocal($cate_id)
    {
        $parents = array();
        $curlocal = array();
        if ($cate_id)
        {
            $parents = $this->_placecate_mod->get_ancestor($cate_id, true);
        }

        foreach ($parents as $category)
        {
            if($category['cate_id'] == $cate_id)
                $curlocal[] = array('text' => $category['cate_name']);
            else
                $curlocal[] = array('text' => $category['cate_name'], 'url' => url('app=place_category&cate_id=' . $category['cate_id']));
        }
        return $curlocal;
    }

    private function _get_seo_info($cate_id)
    {
        $tkd = array(
                'title' => '',
                'keywords' => '艺术摆件,仿真花饰,餐饮用具,家居用品,特色家具',
                'description' => '万菱家饰网提供各种艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具，款式风格选择多，促销优惠最贴心。',
        );
        
        $cates = $this->_placecate_mod->get_ancestor($cate_id, true);
        
        if(count($cates) == 1){
            $tkd = array(
                    'title' => "{$cates[0]['cate_name']}，摆件工艺品，仿真花，酒店装饰品-性福之家",
                    'keywords' => "{$cates[0]['cate_name']}，摆件工艺品，仿真花，酒店装饰品",
                    'description' => "万菱家饰网是广州万菱广场在线家居饰品商城，主营商用家饰与家用饰品的批发和零售，是最大最全的家居饰品网，汇聚广州、深圳、东莞等华南地区的商用家饰、家用饰品品牌，期待并欢迎来万菱家饰网采购及批发www.wljiashi.com",
            );
        }else{
            foreach ($cates as $cate)
            {
                $tkd['title'] = $cate['cate_name'] . '-' . $tkd['title'];
            }
            $tkd['title'] .= "性福之家";
        }
        
        return $tkd;
    }

}
